<?php

namespace App\Store\Controllers\Message;

use App\Admin\Models\SiteCompany;
use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\Member;
use App\Store\Models\Message\Score;
use App\Store\Services\Message\Lianlu;
use App\Store\Services\Message\WxaccountMessage;
use Illuminate\Http\Request;
use App\Store\Validate\Message\Score as ValidateMessageScore;
use Illuminate\Support\Facades\Log;

class ScoreController extends Controller
{
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['title', 'store_ids', 'score_min', 'score_max', 'register_start', 'register_end', 'content']);
        $Validate = new ValidateMessageScore('add');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $store_list = $req_data['store_ids'];
        $store_info_data = is_array($store_list) ? $store_list : (is_array(json_decode($store_list, true)) ? json_decode($store_list, true) : []);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $data = [];
        foreach ($store_info_data as $k => $v) {
            $data[$k]['title'] = $req_data['title'];
            $data[$k]['store_id'] = $v;
            $data[$k]['score_min'] = !empty($req_data['score_min']) ? $req_data['score_min'] : 0;
            $data[$k]['score_max'] = !empty($req_data['score_max']) ? $req_data['score_max'] : 0;
            $data[$k]['register_start'] = !empty($req_data['register_start']) ? $req_data['register_start'] : 0;
            $data[$k]['register_end'] = !empty($req_data['register_end']) ? $req_data['register_end'] : 0;
            $data[$k]['content'] = $req_data['content'];
            $data[$k]['cp_id'] = $cp_id;
            $data[$k]['create_at'] = time();
        }
        Score::insert($data);
        return response()->json(['code' => '000', 'msg' => '添加成功']);
    }

    public function getlist(Request $request)
    {
        $list = Score::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function dodel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateMessageScore('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        Score::where('id', $req_data['id'])->update([
            'is_del' => 2,
            'update_at' => time(),
        ]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'title', 'store_id', 'score_min', 'score_max', 'register_start', 'register_end', 'content']);
        $Validate = new ValidateMessageScore('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $info = Score::where(['id' => $req_data['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->status != 1) {
            return response()->json(['code' => '001', 'msg' => '短信已发送,不可修改']);
        }
        Score::where('id', $req_data['id'])->update([
            'title' => $req_data['title'],
            'content' => $req_data['content'],
            'store_id' => $req_data['store_id'],
            'score_min' => !empty($req_data['score_min']) ? $req_data['score_min'] : 0,
            'score_max' => !empty($req_data['score_max']) ? $req_data['score_max'] : 0,
            'register_start' => !empty($req_data['register_start']) ? $req_data['register_start'] : 0,
            'register_end' => !empty($req_data['register_end']) ? $req_data['register_end'] : 0,

            'update_at' => time(),
        ]);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }


    public function send(Request $request)
    {
        $req_data = $request->only(['id']);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $Validate = new ValidateMessageScore('send');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $one = Score::where(['id' => $req_data['id']])->first();
//        if (!$one || $one['status'] !== 1) {
//            return response()->json(['code' => '001', 'msg' => '发送失败，短信已发送']);
//        }

        if (empty($one)) {
            return response()->json(['code' => '001', 'msg' => '未获取到积分发送模板']);
        }

        $one = $one->toArray();
        //查询用户手机
        $query = Member::where([
            'cp_id' => $one['cp_id'],
            'store_id' => $one['store_id'],
            'is_del'=>1
        ]);

        if ($one['register_start'] > 0 && $one['register_end'] > 0) {
            $query->where('create_at', '>=', $one['register_start'])->where('create_at', '<=', $one['register_end']);
        }

        if ($one['score_min'] > 0 && $one['score_max'] > 0) {
            $query->where('points_current', '>=', $one['score_min'])->where('points_current', '<=', $one['score_max']);
        }

        $list = $query->get()->toArray();

        if (!empty($list)) {
            $phone_arr = array_unique(array_column($list, 'mobile'));
            $content = $one['content'];

            $companyinfo= SiteCompany::where([['id', $cp_id], ['is_open_sms', 2]])->first();
            if (empty($companyinfo)) {
                return response()->json(['code' => '001', 'msg' => '短信未开启']);
            }

            $res = Lianlu::NormalSend($phone_arr, $content, $companyinfo);
            Log::info('积分发送通知结果' . $res);
            $res = (array)json_decode($res, true);
            if (isset($res['message']) && $res['message'] == 'success') {
                Score::where('id', $req_data['id'])->update([
                    'status' => 3,
                    'update_at' => time(),
                ]);
                return response()->json(['code' => '000', 'msg' => '发送成功']);
            } else {
                return response()->json(['code' => '001', 'msg' => '发送失败,'.$res['message']??'']);
            }

        } else {
            return response()->json(['code' => '001', 'msg' => '发送失败，用户为空']);
        }


    }

    public function sendnew(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateMessageScore('send');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $one = Score::where(['id' => $req_data['id']])->first()->toArray();
        if (!$one || $one['status'] !== 1) {
            return response()->json(['code' => '001', 'msg' => '发送失败，短信已发送']);
        }

        //查询用户手机
        $query = Member::where([
            'cp_id' => $one['cp_id'],
            'store_id' => $one['store_id']
        ]);

        if ($one['register_start'] > 0 && $one['register_end'] > 0) {
            $query->where('create_at', '>=', $one['register_start'])->where('create_at', '<=', $one['register_end']);
        }

        if ($one['score_min'] > 0 && $one['score_max'] > 0) {
            $query->where('points_current', '>=', $one['score_min'])->where('points_current', '<=', $one['score_max']);
        }

        $list = $query->get();

        if ($list) {
            $list = $list->toArray();
            $open_id_arr = [];
            foreach ($list as $item) {
                if ($item['wx_account_open_id']) {
                    $open_id_arr[] = $item['wx_account_open_id'];
                }
            }
            $open_id = array_unique($open_id_arr);
            if (empty($open_id)) {
                return response()->json(['code' => '001', 'msg' => '发送失败，用户open_id为空']);
            }

            foreach ($open_id_arr as $open_id) {
                if (!empty($open_id)) {
                    $res = WxaccountMessage::sendwx($one['cp_id'], $open_id, 'score');
                    if ($res['code'] == '0') {
                        return response()->json(['code' => '000', 'msg' => '发送成功']);
                    }
                    return response()->json(['code' => '001', 'msg' => $res['msg']]);
                }
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '发送失败，用户为空']);
        }
    }
}
